#include "Date.h"
#include <cstdio>

//////////////////////////////////////////////////////////////////
//
//     Date class
//
//////////////////////////////////////////////////////////////////

// konstruktory
Date::Date()
{
	time_t now = time(NULL);
	struct tm tm_now = *localtime(&now);
	rok     = tm_now.tm_year + 1900;
	miesiac = tm_now.tm_mon + 1;
	dzien   = tm_now.tm_mday;
}

Date::Date(int m_rok, int m_miesiac, int m_dzien)
{
	rok     = m_rok;
	miesiac = m_miesiac;
	dzien   = m_dzien;
}

std::string Date::ToString()
{
	char buf[50];
	sprintf_s(buf, "%02d.%02d.%04d", dzien, miesiac, rok);
	std::string str(buf);
	return str;
}

//////////////////////////////////////////////////////////////////
//
//     DateDiff class
//
//////////////////////////////////////////////////////////////////

// konstruktory
DateDiff::DateDiff(Date m_from)
{
	lata = 0;
	miesiace = 0;
	dni = 0;
	from = m_from;
	Date now;
	to   = now;
	Calculate();
}

DateDiff::DateDiff(Date m_from, Date m_to)
{
	lata = 0;
	miesiace = 0;
	dni = 0;
	from = m_from;
	to   = m_to;
	Calculate();
}

void DateDiff::Calculate()
{
	// rata die
	int d1 = from.dzien, m1 = from.miesiac, y1 = from.rok;
	if(m1 < 3)
	{
		y1--;
		m1 += 12;
	}
	int days1 = 365 * y1 + y1 / 4 - y1 / 100 + y1 / 400 + (153 * m1 - 457) / 5 + d1 - 306;
	
	int d2 = to.dzien, m2 = to.miesiac, y2 = to.rok;
	if(m2 < 3)
	{
		y2--;
		m2 += 12;
	}
	int days2 = 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 + (153 * m2 - 457) / 5 + d2 - 306;

	dni = days2 - days1;
	miesiace = (to.rok - from.rok) * 12 + to.miesiac - from.miesiac;
	lata = to.rok - from.rok;
}

int DateDiff::IleLat()
{
	return lata;
}

int DateDiff::IleMiesiecy()
{
	return miesiace;
}

int DateDiff::IleDni()
{
	return dni;
}
